package com.siyoumi.app.sys.task;

import com.siyoumi.app.entity.SysOrder;
import com.siyoumi.app.service.SysOrderService;
import com.siyoumi.app.sys.service.IPayOrder;
import com.siyoumi.app.sys.service.payorder.PayOrder;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.task.EnumTask;
import com.siyoumi.task.TaskController;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XSqlStr;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//处理过期订单
//http://dev.x.siyoumi.com/task/sys/task_order_expire_handle
@RestController
@RequestMapping("/task/sys/task_order_expire_handle")
public class TaskOrderExpireHandle
        extends TaskController {

    @Override
    protected Boolean handle1() {
        return false;
    }

    @Override
    protected List handleData() {
        JoinWrapperPlus<SysOrder> query = SysOrderService.getBean().join();
        query.eq("order_pay_ok", 0)
                .eq("order_pay_expire_handle", 0)
                .between("order_pay_expire_date", XDate.now().minusMonths(1), XDate.now()) //只处理1个月内的数据
                .lt("order_pay_expire_handle_date", XDate.now())
                .orderByAsc("order_pay_expire_date");
        int limit = 10;
        if (SysConfig.getIns().isDev()) {
            limit = 1;
        }
        query.last(XSqlStr.limitX(limit));

        return SysOrderService.getBean().get(query);
    }

    @Override
    protected void handleBefore(Object data) {
        SysOrder entity = (SysOrder) data;

        SysOrder entityOrderUpdate = new SysOrder();
        entityOrderUpdate.setOrder_id(entity.getKey());
        entityOrderUpdate.setOrder_pay_expire_handle_date(XDate.now().plusMinutes(3));
        SysOrderService.getBean().updateById(entityOrderUpdate);
    }

    @Override
    protected XReturn handle(Object data) {
        SysOrder entity = (SysOrder) data;
        XHttpContext.setX(entity.getOrder_x_id());

        XApp.getTransaction().execute(status -> {
            IPayOrder app = PayOrder.getIns(entity);
            return app.rollback();
        });


        return EnumTask.RUN.getR();
    }
}
